﻿var Tools = {
    /**
     * 设置Cookie
     * @param {string} key 键
     * @param {any} value 值
     * @param {Date} date 过期时间
     * @param {boolean} overall 是否为全局
     */
    setCookie: function (key, value, date, overall = false) {
        var str = `${key}=${value};expires=${date.toUTCString()}`;
        if (overall) str += ";path=/"
        document.cookie = str;
    },
    /**
     * 返回指定键Cookie
     * @param {string} name
     */
    getCookie: function (key) {
        var strCookies = document.cookie;
        var array = strCookies.split(';');
        for (var i = 0; i < array.length; i++) {
            var item = array[i].split("=");
            if (item[0].trim() == key) { return item[1]; }
        }
        return null;
    },
    /**
     * 删除指定cookie
     * @param {any} key
     */
    delCookie: function (key) {
        var date = new Date();
        date.setTime(date.getTime() - 10);
        document.cookie = key + "= ;" + "expires=" + date.toUTCString();
    },
    /**
     * 快速设置过期时间
     * @param {number} addhours 延期小时数
     */
    getExpires: function (addhours) {
        var date = new Date();
        date.setTime(date.getTime() + (1000 * 60 * 60 * addhours));
        return date;
    },
    /**
     * 获取cookie中的用户对象
     **/
    getUser: function () {
        var user;
        $.get({
            url: "/userinfo/udata",
            async: false,
            dataType: "json",
            success: function (obj) {
                user = obj;
            }
        });
        return user;
    },
    /**
     * 返回购物车列表
     * @returns {Array}
     **/
    getShoppingCar: function () {
        var json = Tools.getCookie("shopCar");
        if (!json) return [];
        var arr = JSON.parse(json);
        return arr;
    },
    /**
     * 设置购物车列表
     * @param {Array} gds
     */
    setShoppingCar: function (gds) {
        var json = JSON.stringify(gds);
        Tools.setCookie("shopCar", json, Tools.getExpires(24), true);
    },
    /**
     * 清除购物车列表
     * */
    delShoopingCar: function () {
        $("#top-shopcard .bylist .list > li").remove();
        updateCarStatus();
        this.delCookie("shopCar");
    },
    /**
     * 添加或覆盖购物车商品单例到cookie
     * @param {number} rushID
     * @param {string} title
     * @param {number} byCount
     * @param {string} src
     */
    addOrUpdateShoppingCarItem: function (rushID, byCount) {
        var gds = Tools.getShoppingCar();
        var cokobj = {
            rushID: parseInt(rushID),
            byCount: parseInt(byCount),
        }
        for (var i = 0; i < gds.length; i++) {
            if (gds[i].rushID == rushID) {
                gds[i] = cokobj;
                Tools.setShoppingCar(gds);
                return;
            }
        }
        gds.push(cokobj);
        Tools.setShoppingCar(gds);
    },
    delShoppingCarItem: function (rushID) {
        var gds = Tools.getShoppingCar();
        for (var i = 0; i < gds.length; i++) {
            if (gds[i].rushID == rushID) gds.splice(i, 1);
        }
        Tools.setShoppingCar(gds);
    },
    showAjaxError: function (jqXHR, textStatus, errorThrown) {
        window.alert(`错误信息:
                          状态码: ${jqXHR.status} 
                          状态信息:${jqXHR.state()}
                          错误类型: ${textStatus} 
                          返回信息: ${errorThrown}`);
    },
    moveToShopCard: function ($cp) {
        var cart = $("#top-shopcard");
        if (cart.length == 0) return;
        console.log("移动!");
        var ct = cart.offset().top;
        var cl = cart.offset().left;
        var sl = $cp.offset().left;
        var st = $cp.offset().top

        anime({
            targets: $cp[0],
            duration: 1000,
            easing: "easeInQuart",
            translateX: (cl - sl),
            translateY: -((st - ct) + 100),
            scale: [1, 0],
            opacity: [1, 0],
            complete: function () {
                $cp.remove();
            }
        })
    },
    /**
     * 添加实例到购物车列表,若已存在则数量加一
     * @param {number} rhid
     * @param {string} title
     * @param {string} src
     * @param {number} byCount
     * @param {number} rem
     */
    addCarItem: function (rhid, title, src, byCount = 1, rem = 9999) {
        //如果商品已存在则加1
        var list = $("#top-shopcard .bylist .list");
        if (list.length == 0) return;
        var items = list.children("li");
        //购物车对象
        var citm = {
            rushID: rhid,
            title: title,
            byCount: byCount,
            src: src
        }
        for (var i = 0; i < items.length; i++) {
            var itm = $(items.get(i));
            if (itm.attr("data-rhid") == rhid) {
                var num = parseInt(itm.find(".input-nud").children("input").val());
                itm.find(".input-nud").children("input").val(++num).change();
                citm.byCount = num;
                updateCarStatus();
                return;
            }
        }
        //添加到购物车cookie
        Tools.addOrUpdateShoppingCarItem(citm.rushID, citm.byCount);
        var caritm = document.createElement("li");
        caritm.className = "item";
        $(caritm).attr("data-rhid", rhid).attr("id", "citm-" + rhid);
        var html = `  <div class="lef">
                                <a href="/Home/GoodAbout?rhid=${rhid}"> <img src="${src}" /></a>
                            </div>
                            <div class="mid blkfont">
                                <h3>${title}</h3>
                                <div class="dt">
                                    <div>
                                        <div onselectstart="return false" class="input-nud">
                                            <button>-</button>
                                            <input type="number" min="1" max="${rem}" value="${byCount}" />
                                            <button>+</button>
                                        </div>
                                        <span>(人次)x 1(元) =</span>
                                        <span class="xj">￥1</span>
                                    </div>
                                </div>
                            </div>
                            <div class="rig">
                                <button class="btn-del layui-btn layui-btn-danger layui-btn-sm">删除</button>
                            </div>`;
        caritm.innerHTML = html;
        $("#top-shopcard .bylist .list").append(caritm);
        var nud = $(caritm).find(".input-nud");
        bindInputNudEvent(nud[0]);
        nud.children("input").change(carBycountChange);
        $(caritm).find(".btn-del").click(carDel);
        updateCarStatus();
    },
    /**
     * 将单件商品前往购买结算
     * @param {number} rhid
     * @param {number} byCount
     */
    settleSingle: function (rhid, byCount) {
        var val = encodeURI(JSON.stringify([{ rushid: rhid, bycount: byCount }]));
        window.location = "/pay/payindex?sig=true&bys=" + val;
    },
    /**
     * 查看夺宝详情
     * @param {number} rhid
     */
    showRobnums: function (rhid) {
        var layload = layer.load(0);
        $.get({
            url: "/userinfo/robdet",
            data: { rhid: rhid },
            dataType: "html",
            success: function (html) {
                layer.open({
                    type: 1,
                    resize: false,
                    title: "&#xe619 云购详情",
                    content: html,
                    area: ["415px", "500px"],
                });
            },
            complete: function () {
                layer.close(layload);
                bindCircleProgbar();
            }
        });
    },
    /**
     * 弹出充值页
     */
    showTopUp: function () {
        $.get({
            url: "/pay/tupage",
            contentType: "html",
            success: function (html) {
                layer.open({
                    type: 1,
                    title: "&#xe613 账户充值",
                    area: ["400px", "300px"],
                    resize: false,
                    content: html,
                });
            }
        })
    },
    /**
     * 发送post请求,并在过程中弹出加载层
     * @param {number} lotype
     * @param {string} url
     * @param {any} data
     * @param {Function} success
     * @param {Function} error
     */
    loadPost: function ({ url, data, success, lotype = 0, error = this.showAjaxError }) {
        var lod = layer.load(lotype);
        $.post({
            url: url,
            data: data,
            success: success,
            error: error,
            complete: function () {
                layer.close(lod);
            }
        })
    },
    /**
     * //生成从minNum到maxNum的随机数
     * @param {number} minNum
     * @param {number} maxNum
     */
    randomNum: function (minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },
    /**绑定商品块事件 */
    bindGdItemBtnEvents: function () {
        //添加到购物车动画
        $(".gd-item .addcar").click(function (e) {
            var $img = $(this).parent().prevAll("a").children("img");
            var $cp = $img.clone();
            $img.parent().parent().append($cp);
            $cp.css("position", "absolute").css("top", "10px").css("left", "20px").css("z-index", "10");
            //购物车添加动画
            Tools.moveToShopCard($cp);
            //添加实际数据
            var tis = $(this);
            var root = tis.parent().parent();
            var rhid = root.attr("data-rhid");//夺宝ID
            var rem = root.attr("data-rem");
            var src = root.children(".gdimg").attr("src");//图片路径
            var title = root.children(".gtitle").text();//商品标题
            Tools.addCarItem(rhid, title, src, 1, rem);
        });

        //立即购买
        $(".gd-item .bynow").click(function () {
            var rhid = parseInt($(this).parents(".gd-item:first").attr("data-rhid"));
            Tools.settleSingle(rhid, 1);
        });
    },
    /**询问登陆 */
    confirmLogin: function () {
        layer.confirm("您还未登陆,是否立即前往登陆?", function (index) {
            window.location = "/userlogin/login";
        });
    }
}

function carBycountChange() {
    var rhid = $(this).parents(".item:first").attr("data-rhid");
    var cont = parseInt($(this).val());
    //var src = $(this).parents(".item:first").children(".lef").children("img").attr("src");
    //var title = $(this).parents(".mid:first").children("h3:first").text();
    Tools.addOrUpdateShoppingCarItem(rhid, cont);
    updateCarStatus();
}

function carDel() {
    var rhid = $(this).parents(".item:first").attr("data-rhid");
    Tools.delShoppingCarItem(rhid);
    $(this).parent().parent().remove();
    updateCarStatus();
}

function updateCarStatus() {
    var list = $("#top-shopcard .bylist .list");
    var items = list.children("li");
    var cont = items.length;
    $("#card-count").text(cont);//更新数量
    var sum = 0;
    //更新所有商品数据
    for (var i = 0; i < items.length; i++) {
        var item = $(items.get(i));
        var $xj = item.find(".xj");
        var bycont = parseInt(item.find(".input-nud").children("input").val());
        sum += bycont;
        $xj.text("￥" + bycont).attr("data-value", bycont);
    }
    //更新统计数据
    $("#top-shopcard .tj .ct").text(items.length);
    $("#top-shopcard .tj .moy").text("￥" + sum);
}
